import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author MaoLin Wang
 * @description
 * @date 2020/9/2 3:50 下午
 */
public class ReadWriteLock {
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10000; i++) {
            new Thread(()->secKill()).start();
        }
        countDownLatch.await();
        System.out.println("失败次数\t"+failureCount.get());
        System.out.println("成功次数\t"+successCount.get());
    }
    public static boolean secKill(){
        if (!semaphore.tryAcquire()){
            System.out.println("系统繁忙");
            failureCount.incrementAndGet();
            countDownLatch.countDown();
            return false;
        }
        System.out.println("开始秒杀");
        try {
            Thread.sleep(random.nextLong(300));
            System.out.println("秒杀成功，订单id--->"+successCount.getAndIncrement());
            countDownLatch.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            semaphore.release(45);
        }
        return true;
    }

    private static ThreadLocalRandom random=ThreadLocalRandom.current();
    private  static CountDownLatch countDownLatch=new CountDownLatch(10000);
    private static Semaphore semaphore = new Semaphore(1000);
    private static AtomicInteger failureCount = new AtomicInteger(0);
    private static AtomicInteger successCount=new AtomicInteger(0);

}
